// 获取DOM元素
const chatContent = document.getElementById('chatContent');
const modelSelect = document.getElementById('modelSelect');
const messageInput = document.getElementById('messageInput');
const sendButton = document.getElementById('sendButton');
const typingIndicator = document.querySelector('.typing-indicator');
const inputArea = document.querySelector('.input-area');
const fileInput = document.getElementById('fileInput');
const fileListArea = document.getElementById('fileListArea');
const fileListContent = document.getElementById('fileListContent');
const clearAllFilesButton = document.getElementById('clearAllFilesButton');

// 存储上传的文件
let uploadedFiles = [];

// 显示正在回答的提示
function showTypingIndicator() {
    if (typingIndicator.parentNode !== chatContent) {
        chatContent.appendChild(typingIndicator);
    }
    typingIndicator.classList.add('show');
    inputArea.classList.add('disabled');
    typingIndicator.scrollIntoView({ behavior: 'smooth', block: 'end' });
}

// 隐藏正在回答的提示
function hideTypingIndicator() {
    typingIndicator.classList.remove('show');
    inputArea.classList.remove('disabled');
}

// 消息展示功能
function appendMessage(role, content, model = null) {
    const messageDiv = document.createElement('div');
    if (role === 'assistant' && model) {
        const modelClass = model.toLowerCase();
        messageDiv.className = `message ${role}-message model-${modelClass}`;
    } else {
        messageDiv.className = `message ${role}-message`;
    }

    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';

    if (role === 'system' && model) {
        const textNode = document.createTextNode(content + '申请地址：');
        messageContent.appendChild(textNode);

        const linkElement = document.createElement('a');
        linkElement.href = model;
        linkElement.target = '_blank';
        linkElement.rel = 'noopener noreferrer';
        linkElement.className = 'api-key-link';
        linkElement.textContent = model;
        messageContent.appendChild(linkElement);
    } else {
        messageContent.innerHTML = content;
    }

    const messageFooter = document.createElement('div');
    messageFooter.className = 'message-footer';

    const timeDiv = document.createElement('div');
    timeDiv.className = 'message-time';
    timeDiv.textContent = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });

    if (role === 'assistant' && model) {
        const modelDiv = document.createElement('div');
        const modelClass = model.toLowerCase();
        modelDiv.className = `message-model model-${modelClass}`;

        let modelDisplayName = '';
        switch (model.toLowerCase()) {
            case 'ernie':
                modelDisplayName = '文心一言';
                break;
            case 'deepseek':
                modelDisplayName = '深度求索';
                break;
            case 'qwen':
                modelDisplayName = '通义千问';
                break;
            default:
                modelDisplayName = model;
        }

        modelDiv.textContent = modelDisplayName;
        messageFooter.appendChild(modelDiv);
    }

    messageFooter.appendChild(timeDiv);
    messageDiv.appendChild(messageContent);
    messageDiv.appendChild(messageFooter);

    chatContent.insertBefore(messageDiv, typingIndicator);
    messageDiv.scrollIntoView({ behavior: 'smooth', block: 'end' });
    chatContent.scrollTop = chatContent.scrollHeight;
}

// 更新文件列表显示
function updateFileList() {
    fileListContent.innerHTML = '';
    uploadedFiles.forEach((file, index) => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';

        // 计算文件大小显示
        const fileSize = formatFileSize(file.size);

        fileItem.innerHTML = `
            <i class="fas fa-file-excel file-icon"></i>
            <div class="file-info">
                <span class="file-name">${file.name}</span>
                <span class="file-size">${fileSize}</span>
            </div>
            <i class="fas fa-times remove-file" data-index="${index}"></i>
        `;
        fileListContent.appendChild(fileItem);
    });

    fileListArea.style.display = uploadedFiles.length > 0 ? 'block' : 'none';
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 文件选择处理
fileInput.addEventListener('change', function(e) {
    const files = Array.from(e.target.files);
    const maxFileSize = 10 * 1024 * 1024; // 10MB
    const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel'
    ];

    files.forEach(file => {
        if (!allowedTypes.includes(file.type)) {
            alert(`文件 ${file.name} 不是有效的Excel文件，请只上传.xlsx或.xls格式的文件`);
            return;
        }

        if (file.size > maxFileSize) {
            alert(`文件 ${file.name} 超过大小限制（10MB），请上传更小的文件`);
            return;
        }

        // 检查是否已存在同名文件
        if (uploadedFiles.some(f => f.name === file.name)) {
            alert(`文件 ${file.name} 已经上传过了`);
            return;
        }

        uploadedFiles.push(file);
    });

    updateFileList();
});

// 清除单个文件
fileListContent.addEventListener('click', function(e) {
    if (e.target.classList.contains('remove-file')) {
        const index = parseInt(e.target.dataset.index);
        uploadedFiles.splice(index, 1);
        updateFileList();
    }
});

// 清除所有文件
clearAllFilesButton.addEventListener('click', function() {
    uploadedFiles = [];
    fileInput.value = '';
    updateFileList();
});

// 消息发送函数
async function sendMessage() {
    const message = messageInput.value.trim();
    const selectedModel = modelSelect.value;

    if (!message) return;

    if (message) appendMessage('user', message);
    messageInput.value = '';

    showTypingIndicator();

    try {
        const formData = new FormData();
        formData.append('model', selectedModel);
        formData.append('message', message);

        uploadedFiles.forEach((file, index) => {
            formData.append(`file${index}`, file);
        });

        const response = await fetch('api.php', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();
        console.log('API响应数据:', data);

        if (data.error) {
            console.error('API错误:', data.error);
            if (data.link) {
                appendMessage('system', data.error, data.link);
            } else {
                appendMessage('system', data.error);
            }
            return;
        }

        if (!data.content) {
            console.error('API响应缺少content字段:', data);
            appendMessage('system', '服务器返回数据格式错误');
            return;
        }

        appendMessage('assistant', data.content.html, selectedModel);
    } catch (error) {
        console.error('请求失败:', error);
        appendMessage('system', `服务请求失败: ${error.message}`);
    } finally {
        hideTypingIndicator();
    }
}

// 输入框回车发送
messageInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

// 添加按钮点击事件监听
sendButton.addEventListener('click', sendMessage);

// 点击上传按钮触发文件选择
document.getElementById('uploadButton').addEventListener('click', function() {
    fileInput.click();
});